package member;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.jdo.Transaction;

import java.util.List;
import shared.PMF;
import member.Member;

//import shared.PMF;
//import javax.jdo.PersistenceManager;

public class SaveScore extends HttpServlet {

	private static final long serialVersionUID = 1L;
	private static final String nextJSP = "/mem/stockScore.jsp";

	@SuppressWarnings("unchecked")
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {
		String score = request.getParameter("score");
		int sum = 0;
		if(score.equals("一星")){
			sum = 1;
		}else if(score.equals("二星")){
			sum = 2;
		}else if(score.equals("三星")){
			sum = 3;
		}else if(score.equals("四星")){
			sum = 4;
		}else if(score.equals("五星")){
			sum = 5;
		}
		
		response.setContentType("text/html;charset=BIG5");
		request.setCharacterEncoding("BIG5");
		
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Transaction tx = pm.currentTransaction();
		
		Query query = pm.newQuery(Member.class);
		query.setFilter("transTimes >= 0");
		Long memberID = (long) 1;
		List<Member> results = (List<Member>) query.execute();
		for (Member m : results) {
			if(m.getName().equals("dollc2005")){
				memberID = m.getId();
				break;
			}
		}
		
		
		try{
			tx.begin();
			Member p = pm.getObjectById(Member.class, memberID);
			p.averageScore(sum);
		    pm.makePersistent(p);
		    tx.commit();
		} finally {
            if (tx.isActive()) {
                tx.rollback();
            }
		    pm.close();
		}
		
		response.sendRedirect(nextJSP);
		
	}//doGet
	public void doPost(HttpServletRequest request, HttpServletResponse response) 
	throws IOException, ServletException{
		doGet(request, response);
	}
}
